package controller;

import java.io.IOException;
import java.sql.SQLException;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import sql.*;
import bean.*;

public class Confirmation extends HttpServlet 
{
	HttpSession session;
	TransactionLookUp transactionLookUp;
	FinanceAccountBean finance;
	FinanceAccountLookUp financeAccountLookUp;
	HashMap<Integer, BookBean> cartList;
		
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	{
	 session = request.getSession(true);
	 transactionLookUp = new TransactionLookUp();
	 financeAccountLookUp = new FinanceAccountLookUp();
	 String confirm = request.getParameter("confirm");
	 String address = "";
	 
	 try 
		{
			if(confirm != null)
			{
				cartList = (HashMap<Integer, BookBean>)session.getAttribute("cart");
				finance = (FinanceAccountBean)session.getAttribute("financeAccount");
				
				Double cartTotalAmount = getCartTotalAmount();				
				if(checkFinance(cartTotalAmount))
				{
					int transactionNumber = createBookTransaction();
					createTransactionLine(transactionNumber);
					updateBookStatus();
					updateDevilpepperAccount();
					updateSellerFinanceAccount();
					updateBuyerFinanceAccount();
					if(session.getAttribute("cart") != null){session.removeAttribute("cart");};
					if(session.getAttribute("cartItemCount") != null){session.removeAttribute("cartItemCount");};
					session.setAttribute("transactionNumber", transactionNumber);
			
					address = "/WEB-INF/confirmation.jsp";
				}
				else
				{ //TODO: display not sufficient
				}
			}
			else
			{				
				address= "/WEB-INF/checkout.jsp";						
			}
			
			RequestDispatcher dispatcher = request.getRequestDispatcher(address);
			dispatcher.forward(request, response);
		} catch (ServletException e) { e.printStackTrace();
		} catch (IOException e) { e.printStackTrace();
		} catch (ClassNotFoundException e) {e.printStackTrace();
		} catch (SQLException e) {e.printStackTrace();
		}		
	}
	
	
	private Double getCartTotalAmount() 
	{
		Double itemTotal = 0.0;
	   	Double shippingCost = 4.99;
	   	DecimalFormat df = new DecimalFormat("##.00");		
	
		for(BookBean book: cartList.values()) 
		{				
			itemTotal += book.getPrice();
			df.format(itemTotal);     
		}				
		return itemTotal + shippingCost;
	}

	public boolean checkFinance(double cartTotalAmount)
	{
		boolean canMakePurchase = false;
		
		//assuming buyer can only use their credit card 
		if(cartTotalAmount <= finance.getCreditCardBalance())
		{
			canMakePurchase = true;
		}		
		return canMakePurchase;
	}
	
	private int createBookTransaction() throws ClassNotFoundException, SQLException 
	{
		DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
		Date date = new Date();		
		String currentDate = dateFormat.format(date).toString();
		
		transactionLookUp.createBookTransaction(currentDate, finance.getCustomerId(), finance.getCreditCardAccountId());
		return transactionLookUp.getBookTransaction(finance.getCustomerId(), finance.getCreditCardAccountId());
	}
	
	private void createTransactionLine(int transactionNumber) throws ClassNotFoundException, SQLException 
	{
		ArrayList<Integer> cartBookId = getCartBookIdList();		
		transactionLookUp.createTransactionLine(transactionNumber, cartBookId);
	}

	private void updateBookStatus() throws ClassNotFoundException, SQLException 
	{
		ArrayList<Integer> cartBookId = getCartBookIdList();
		
		transactionLookUp.updateBookStatus(cartBookId);
	}
	
	private ArrayList<Integer> getCartBookIdList() 
	{
		ArrayList<Integer> cartBookId = new ArrayList<Integer>();		
		for(BookBean book: cartList.values()) 
		{
			cartBookId.add(book.getBookId());
		}
		return cartBookId;
	}
	
	private void updateDevilpepperAccount() throws ClassNotFoundException, SQLException
	{		
		Integer devilPepperAccountId = 1;		
		for(BookBean book: cartList.values())
		{			
			//devilpepper gets 10% of book
			Double payment = 0.10 * book.getPrice();
			FinanceAccountBean sellerFinance = financeAccountLookUp.getCustomerFinanceAccount(devilPepperAccountId);
			transactionLookUp.addFinance(sellerFinance.getPaypalAccountId(), payment);
		}
	}
	
	private void updateSellerFinanceAccount() throws ClassNotFoundException, SQLException 
	{
		for(BookBean book: cartList.values())
		{			
			//seller gets whatever left after 10% is given to devilpepper account
			Double payment = book.getPrice() - (0.10 * book.getPrice());
			FinanceAccountBean sellerFinance = financeAccountLookUp.getCustomerFinanceAccount(book.getSellerId());
			transactionLookUp.addFinance(sellerFinance.getPaypalAccountId(), payment);
		}
	}
	
	private void updateBuyerFinanceAccount() throws ClassNotFoundException, SQLException 
	{
		transactionLookUp.deductFinance(finance.getCreditCardAccountId(), getCartTotalAmount());
	}

}
